package com.js.downloadmanagerdemo.downloader;

// Created by JS on 2021/6/25.

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.js.downloadmanagerdemo.BuildConfig;

import java.io.File;
import java.lang.ref.WeakReference;

public class DownLoaderUtils {

    private static final String TAG = "DownLoaderUtils";

    private Context context;

    private WeakReference<Context> weakReference = null;
    private Long downloadId = 0L;

    public DownLoaderUtils(Context context) {
        this.context = context;
        weakReference = new WeakReference<>(context);
    }

    /**
     * 直接下载apk，下载完成之后无需安装apk
     * @param title
     * @param url
     */
    public void downloadApk(String title, String url) {
        downloadApk(title, url, false);
    }

    /**
     * 下载apk并判断是否需要
     * @param title
     * @param url
     * @param needInstall
     */
    public void downloadApk(String title, String url, boolean needInstall) {
        if (weakReference != null && weakReference.get() != null) {
            Context context = weakReference.get();
            // 这边是初始化download错误的时候
            String fileName;
            if (url.contains(".apk")) {
                fileName = url.substring(url.lastIndexOf("/"), url.length());
            } else {
                fileName = "axe_" + System.currentTimeMillis() + ".apk";
            }

            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName);
            // 假如这个apk已经下载了，然后需要直接安装，那么就直接安装
            if (file.exists() && needInstall) {
                install(context, file.getAbsolutePath());
                return;
            }

            Toast.makeText(context,"正在下载" + title, Toast.LENGTH_SHORT).show();
            // 真正的下载逻辑
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setTitle(title);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setMimeType("application/vnd.android.package-archive");
            if (TextUtils.isEmpty(title)) {
                request.setDescription(fileName);
            } else {
                request.setDescription(title);
            }

            try {
                if (DownLoaderManager.downloadManager == null) {
                    // 可能部分机型不支持这个DownloaderManger ，这边可以使用自定义的下载框架
                    return;
                }
                request.setDestinationUri(Uri.fromFile(file));
                if (DownLoaderManager.downloadManager != null) {
                    downloadId = DownLoaderManager.downloadManager.enqueue(request);
                    DownloadBean downloadBean = new DownloadBean();
                    downloadBean.downloadId = downloadId;
                    downloadBean.title = title;
                    downloadBean.downloadType = DownloadBean.TYPE_APK;
                    downloadBean.needInstall = needInstall;
                    DownLoaderManager.downloadList.add(downloadBean);
                } else {
                    // 有些机型没有downloadManager，这里跳转浏览器下载
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(url);
                    intent.setData(content_url);
                    context.startActivity(intent);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }



        }
    }

    private void install(Context context, String filePath) {
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 下载文件
     */
    public void downloadFile(String title, String url, String fileName) {
        if (weakReference != null && weakReference.get() != null) {
            Context context = weakReference.get();
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setTitle(title);
            request.setDescription(title);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            String saveFile;
            if (TextUtils.isEmpty(fileName)) {
                saveFile = url.substring(url.lastIndexOf("/"), url.length());
            } else {
                saveFile = fileName;
            }

            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), saveFile);
            Log.d(TAG, "文件地址：" + file.getPath());
            request.setDestinationUri(Uri.fromFile(file));
            if (DownLoaderManager.downloadManager != null) {
                downloadId = DownLoaderManager.downloadManager.enqueue(request);
                DownloadBean downloadBean = new DownloadBean();
                downloadBean.downloadId = downloadId;
                downloadBean.title = title;
                downloadBean.downloadType = DownloadBean.TYPE_FILE;
                DownLoaderManager.downloadList.add(downloadBean);
            }
        }
    }
}
